<template>
  <div>
    <el-upload
      action="#"
      list-type="picture-card"
      :auto-upload="true"
      :file-list="fileList"
      :http-request="uploadFile"
      :limit="fileLength"
      :on-exceed="handleExceed"
      accept=".jpg,.jpeg,.png,.JPG,.JPEG"
    >
      <i slot="default" class="el-icon-plus"></i>
      <div slot="file" slot-scope="{ file }">
        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
        <span class="el-upload-list__item-actions">
          <span
            class="el-upload-list__item-preview"
            @click="handlePictureCardPreview(file)"
          >
            <i class="el-icon-zoom-in"></i>
          </span>
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleRemove(file)"
          >
            <i class="el-icon-delete"></i>
          </span>
        </span>
      </div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>
<script>
import { getUUID } from "@/utils";
import { ossUpload } from "@/utils/ossUpload";
export default {
  name: "uploadimg",
  data() {
    return {
      fileLength: 4,
      dialogImageUrl: "",
      dialogVisible: false,
      disabled: false,
      fileList: [],
    };
  },
  watch : {
      fileList(newValue,oldValue){
      }
  },
  methods: {
    handleRemove(file) {
     for(let i = 0;i < this.fileList.length;i++){
         if(this.fileList[i].uid == file.uid){
             this.fileList.splice(i,1)
             this.$emit('submitImg',this.fileList)
             break;
         }
     }
    },
    clearImg(){
      while(this.fileList.length > 0){
        this.fileList.pop()
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleDownload(file) {
      this.$message.info("暂不支持下载图片");
    },
    uploadFile(params) {
      ossUpload(params.file).then((res) => {
        this.fileList.push({
          name: params.file.name,
          url: res.url,
        });
        this.$emit('submitImg',this.fileList)
        this.$message.success("上传成功");
      });
    },
    handleExceed(files, fileList) {
      this.$message.warning("最多只能上传4张图片");
    },
  },
};
</script>